import { ServiceProxy, UserInfoDTO, RoleInfoDTO, SiteDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { finalize } from 'rxjs/operators';
import { SetUserReasonModalComponent } from './set-user-reason-modal/set-user-reason-modal.component';
import { EditUserModalComponent } from './edit-user-modal/edit-user-modal.component';
import { SetPasswordModalComponent } from './set-password-modal/set-password-modal.component';
import { FileUploader } from 'ng2-file-upload';
import { AppConsts } from '@shared/AppConsts';


@Component({
  selector: 'app-user-management',
  templateUrl: './user-management.component.html',
  styleUrls: ['./user-management.component.less']
})
export class UserManagementComponent extends AppComponentBase implements OnInit {
  @ViewChild('setUserReasonModal') setUserReasonModal: SetUserReasonModalComponent;
  @ViewChild('editUserModal') editUserModal: EditUserModalComponent;
  @ViewChild('setPasswordModal') setPasswordModal: SetPasswordModalComponent;
  @ViewChild('fileSelect') uploadImg: any;
  uploader: FileUploader;

  tableHelper: NzTableHelper;
  loading = true;
  keyword: string;
  roleIdParam: string;
  siteId: string;
  roles: RoleInfoDTO[] = [];
  sites: SiteDTO[] = [];

  constructor(injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  getRoles(): void {
    this._service.getAllRoleInfosUsingGET().subscribe(result => {
      this.roles = result.result.fieldList;
    });
  }

  getSites(): void {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    });
  }

  ngOnInit() {

    this.keyword = undefined;
    this.roleIdParam = '';
    this.siteId = '';

    this.getRoles();
    this.getSites();
    this.load();
    this.initUploaders();
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getAllUserInfosUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword, this.roleIdParam, this.siteId
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }

  reset() {
    this.tableHelper.pageIndex = 1;
    this.keyword = undefined;
    this.roleIdParam = '';
    this.siteId = '';
    this.load();
  }

  editUser(userId?: string): void {
    this.editUserModal.show(userId);
  }

  setUserReason(user: UserInfoDTO) {
    this.setUserReasonModal.show(user.id, user.usedFlag);
  }

  setPwd(id: string) {
    this.setPasswordModal.show(id);
  }


  initUploaders(): void {
    this.uploader = new FileUploader({
      url: AppConsts.serverBaseUrl + '/api/siiat/v1/userinfos/batchImport',
      method: 'POST',
      authToken: 'Bearer ' + abp.auth.getToken(),
      removeAfterUpload: true,
      autoUpload: true
    });
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };

    this.uploader.onSuccessItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      if (ajaxResponse.success) {
        this.message.success(this.l('upload_success'));
      } else {
        this.message.error(this.l(ajaxResponse.error.message));
      }

      this.uploader.destroy();
      this.initUploaders();
      this.imgCropper();
      this.load();
    };
    this.uploader.onErrorItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      this.message.error(this.l(ajaxResponse.error.message));
      this.imgCropper();
    };
  }

  
  imgCropper() {
    // 一系列操作
    // 最后把input的value置空
    this.uploadImg.nativeElement.value = '';
  }

}
